class Solution {
public:
    int trap(vector<int>& height) {
        int n=height.size();
        int l=1;
        int r=n-2;
        int lmax=height[0];
        int rmax=height[n-1];
        int ans=0;
        while(l<=r)
        {
            if(lmax<=rmax)
            {
                ans+=max(0,lmax-height[l]);
                lmax=max(height[l++],lmax);
            }
            if(lmax>rmax)
            {
                ans+=max(0,rmax-height[r]);
                rmax=max(height[r--],rmax);
            }
        }
        return ans;
    }
};